package com.bbg.amyam.web.util.view;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bbg.amyam.web.util.menu.MenuItem;

public class DomainClassNameUpdator extends AbstractGenerator {
	private static final Log log = LogFactory.getLog(DomainClassNameUpdator.class);
	public DomainClassNameUpdator(MenuItem item, boolean overwrite) {
		super(item, overwrite);
	}

	@Override
	public void execute() throws IOException {
		String domainPackagePath = this.getDomainClassPackagePath();
		String requestPaserPath = this.getRequestPaserClassPath();
		File domainPackage=new File(domainPackagePath);
		File requestPaser=new File(requestPaserPath);
		List<String> lines = FileUtils.readLines(requestPaser);
		ArrayList<String> newLines=new ArrayList<String>();
		boolean rmv=false;
		for(String line:lines){
			if(line.indexOf("DONT REMOVE START") > -1){
				newLines.add(line);
				rmv=true;
			}
			if(line.indexOf("DONT REMOVE END") > -1){
				rmv=false;
				line=update(line,domainPackage);
			}
			if(!rmv){
				newLines.add(line);
			}
		}
		
		FileUtils.writeLines(requestPaser,newLines);
		log.debug("Updated "+ requestPaserPath );
	}

	private String update(String line, File domainPackage) {
		Collection<File> files = FileUtils.listFiles(domainPackage,new String[] {"java"},false);
		String newline="";
		for(File file:files){
			String domainName=StringUtils.replace(file.getName(),".java","");
			domainName=domainName.toLowerCase();
			newline += "DOMAIN_CLASSES.add(\""+domainName+"s\");\n";
			log.debug("Request parser added domain name: "+ domainName );
		}
		
		line=newline+"\n"+line;
		return line;
	}

}
